package com.example.kotlinlearn.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.widget.Toast

import com.example.kotlinlearn.BaseActivity
import com.example.kotlinlearn.R
import com.example.kotlinlearn.databinding.ActivityBroadcastBinding

class BroadcastActivity : BaseActivity() {

    lateinit var timeChangeReceiver: TimeChangeReceiver

    private lateinit var binding: ActivityBroadcastBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_broadcast)
        binding = ActivityBroadcastBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val intentFilter = IntentFilter()
        intentFilter.addAction("android.intent.action.TIME_TICK")
        timeChangeReceiver = TimeChangeReceiver()
        registerReceiver(timeChangeReceiver,intentFilter)
        binding.sendBroadcast.setOnClickListener {
            //发送广播
            val intent = Intent("com.example.bim.broadcastTest.MY_BROADCAST")
            //使其成为一条显示广播
            intent.setPackage(packageName)
            sendBroadcast(intent)
        }
        binding.unLoginBroadcast.setOnClickListener {
            val intent =Intent("com.example.bim.UnLogin")
            intent.setPackage(packageName)
            sendBroadcast(intent)
        }
    }

    //在活动销毁时取消广播接收
    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(timeChangeReceiver)
    }

    inner class TimeChangeReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            Toast.makeText(context,"时间滴答滴答",Toast.LENGTH_SHORT).show()
            binding.broadCastTextView.setText(Math.random().toString())
        }
    }
}